import { defineStore } from "pinia";
import request from '@/utils/request';
import { ApiRes } from '@/types/data'
import { CartItem } from '@/types/cart'
import useStore from "..";



const useCartStore = defineStore('cart', {
  state() {
    return {
      list: [] as CartItem[]
    }
  },
  persist: {
    key: 'rabbit-cart-93'
  },
  getters: {
    isLogin(): boolean {
      const { user } = useStore()
      return !!user?.profile?.token
    },
    effectiveList(): CartItem[] {
      return this.list.filter((item) => item.isEffective && item.stock > 0)
    },
    effectiveListCounts(): number {
      return this.effectiveList.reduce((sum, item) =>
        sum + item.count
        , 0)
    },
    effectiveListPrice(): string {
      return this.effectiveList.reduce((sum, item) => sum + item.count * Number(item.nowPrice), 0).toFixed(2)
    },
    isAllSelected(): boolean {
      return this.effectiveList.every(item => item.selected) && this.effectiveList.length !== 0
    },
    selectedList(): CartItem[] {
      return this.effectiveList.filter((item) => item.selected)
    },
    selectedListCounts(): number {
      return this.selectedList.reduce((sum, item) => sum + item.count, 0)
    },
    selectedListPrice(): string {
      return this.selectedList.reduce((sum, item) => sum + item.count * +item.nowPrice, 0).toFixed(2)
    }

  },
  actions: {

    async getCartList() {
      if (this.isLogin) {
        const res = await request.get<ApiRes<CartItem[]>>('/member/cart')
        this.list = res.data.result
      } else {
        // 遍历发请求，校验更新sku商品的库存和价格，是否有效
        this.list.forEach(async cartItem => {
          const { skuId } = cartItem
          // 根据skuId获取最新商品信息
          const res = await request.get<ApiRes<CartItem>>(`/goods/stock/${skuId}`)
          // 保存最新商品信息
          const lastCartInfo = res.data.result
          // 更新商品现价
          cartItem.nowPrice = (+lastCartInfo.nowPrice).toFixed(2)
          // 更新商品库存
          cartItem.stock = lastCartInfo.stock
          // 更新商品是否有效
          cartItem.isEffective = lastCartInfo.isEffective
        })
      }
    },
    async addCart(data: CartItem) {
      if (this.isLogin) {
        await request.post('/member/cart', { skuId: data.skuId, count: data.count })
        this.getCartList()
      } else {
        console.log('本地添加');
        let goods = this.list.find(item => item.skuId === data.skuId)
        if (goods) {
          goods.count += data.count
        } else {
          this.list.unshift(data)
        }
      }

    },
    async updateCart(skuId: string, data: { selected?: boolean, count?: number }) {
      if (this.isLogin) {
        await request.put(`/member/cart/${skuId}`, data)
        this.getCartList()
      } else {
        const goods = this.effectiveList.find(item => item.skuId === skuId)
        if (data.selected !== undefined) {
          goods!.selected = data.selected
        }
        if (data.count !== undefined) {
          goods!.count = data.count
        }
      }
    },
    async deleteCart(skuIds: string[]) {
      if (this.isLogin) {
        await request.delete('/member/cart', {
          // params中传递的参数，往地址栏拼接的
          // data中传递的参数，往请求体中包装的
          // delete支持在请求体中传参
          data: {
            ids: skuIds
          }
        })
        this.getCartList()
      } else {
        this.list = this.list.filter(item => !skuIds.includes(item.skuId))
      }

    },
    async updateCartAllSelected(isSelected: boolean) {
      if (this.isLogin) {
        await request.put('/member/cart/selected', {
          selected: isSelected
        })
        this.getCartList()
      } else {
        this.list.forEach(item => item.selected = isSelected)
      }
    },
    clearCart() {
      this.list = []
    },
    // 合并购物车
    async mergeLocalCart() {
      const data = this.list.map(item => {
        return {
          skuId: item.skuId,
          selected: item.selected,
          count: item.count
        }
      })
      await request.post('/member/cart/merge', data)
      // 合并成功，重新获取购物车列表
      this.getCartList()
    }
  }
});

export default useCartStore;